package com.synnex.mobile.servier.core.msgBoard.service.impl;

import com.synnex.mobile.generic.core.pager.DataResults;
import com.synnex.mobile.generic.core.pager.Pagination;
import com.synnex.mobile.generic.core.util.ObjectUtil;
import com.synnex.mobile.servier.core.msgBoard.bo.MsgBo;
import com.synnex.mobile.servier.core.msgBoard.bo.criteria.MsgBoardCriteria;
import com.synnex.mobile.servier.core.msgBoard.dao.MsgBoardDao;
import com.synnex.mobile.servier.core.msgBoard.dto.MsgDTO;
import com.synnex.mobile.servier.core.msgBoard.service.MsgBoardService;
import com.synnex.mobile.servier.core.service.impl.AbstractServiceImpl;
import com.synnex.mobile.servier.core.updateTime.bo.UpdateTime;
import com.synnex.mobile.servier.core.updateTime.dto.UpdateTimeDTO;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: kerryf
 * To change this template use File | Settings | File Templates.
 */
@Transactional
public class MsgBoardServiceImpl extends AbstractServiceImpl implements MsgBoardService {

    protected MsgBoardDao msgBoardDao;


    public void setMsgBoardDao(MsgBoardDao msgBoardDao) {
        this.msgBoardDao = msgBoardDao;
    }

    public DataResults<MsgBo> getMsgList(MsgBoardCriteria criteria) {

        MsgDTO msgDTO = new MsgDTO();
        Pagination pagination = criteria.getPagination();
        List<MsgDTO> msgDTOList = msgBoardDao.getMsgList(msgDTO, pagination.getBegin(), pagination.getPageSize());
        Integer size = msgBoardDao.getMsgSize(msgDTO);

        DataResults<MsgBo> data = DataResults.create(size, MsgBo.createListInstances(msgDTOList), pagination);
        return data;
    }

    public void saveMsg2MsgBoard(MsgBo msgBo) {
        MsgDTO msg = ObjectUtil.copyProperties(msgBo,MsgDTO.class);
        msg.setEntryDate(new Date());
        msg.setSeq(0);
        msgBoardDao.saveMsg(msg);

        Integer msgCount = msgBoardDao.getMsgSize(new MsgDTO());
        boolean flag = (msgCount % 10) == 0;
        int lastPage =  flag ? (msgCount / 10) : (msgCount / 10) + 1;

        UpdateTimeDTO up  = new UpdateTimeDTO();
        UpdateTimeDTO temp = new UpdateTimeDTO();
        temp.setUrl("/mobile/msgBoard/listMsg.do?pageNo="+lastPage);
        List<UpdateTimeDTO> data = updateTimeDao.getUpdateTimeDTO(temp);
        if (null != data && data.size() > 0) {
            up =  data.get(0);
            up.setUpdateTime(System.currentTimeMillis());
            updateTimeDao.mergeUpdateTimeDTO(up);
        }

    }
}
